<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑标签' : '新增标签'"
    width="500px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="80px"
      class="tag-form"
    >
      <el-form-item label="标签名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入标签名称"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="标签颜色" prop="color">
        <div class="color-picker-row">
          <el-color-picker
            v-model="formData.color"
            :predefine="TAG_COLORS"
            show-alpha
            @change="handleColorChange"
          />
          <el-input
            v-model="formData.color"
            placeholder="或输入颜色代码"
            style="width: 140px; margin-left: 15px;"
            @input="handleColorInput"
          />
        </div>
      </el-form-item>
      
      <el-form-item label="预览效果">
        <el-tag
          v-if="formData.color && formData.name"
          :color="formData.color"
          :style="{ color: getTextColor(formData.color) }"
          size="large"
          class="color-preview"
        >
          {{ formData.name || '标签预览' }}
        </el-tag>
        <span v-else class="preview-placeholder">请输入标签名称和选择颜色</span>
      </el-form-item>
      
      <el-form-item label="预设颜色">
        <div class="preset-colors">
          <div
            v-for="color in TAG_COLORS"
            :key="color"
            class="preset-color-item"
            :class="{ active: formData.color === color }"
            :style="{ backgroundColor: color }"
            @click="selectPresetColor(color)"
          >
            <el-icon v-if="formData.color === color" color="#fff" size="16">
              <Check />
            </el-icon>
          </div>
        </div>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Check } from '@element-plus/icons-vue'
import { createTag, updateTag, TAG_COLORS } from '../../../api/tag'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  tagData: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible', 'success'])

// 表单引用
const formRef = ref()

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 是否为编辑模式
const isEdit = computed(() => !!props.tagData?.id)

// 提交加载状态
const submitLoading = ref(false)

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  color: '#409EFF'
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 1, max: 20, message: '标签名称长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  color: [
    { required: true, message: '请选择标签颜色', trigger: 'change' },
    { pattern: /^#[0-9A-Fa-f]{6}$/, message: '请输入正确的颜色代码格式', trigger: 'blur' }
  ]
}

// 计算文字颜色（根据背景色深浅）
const getTextColor = (backgroundColor) => {
  if (!backgroundColor) return '#333'
  
  // 去掉#号
  const hex = backgroundColor.replace('#', '')
  
  // 转换为RGB
  const r = parseInt(hex.substr(0, 2), 16)
  const g = parseInt(hex.substr(2, 2), 16)
  const b = parseInt(hex.substr(4, 2), 16)
  
  // 计算亮度
  const brightness = (r * 299 + g * 587 + b * 114) / 1000
  
  // 根据亮度返回黑色或白色文字
  return brightness > 128 ? '#333' : '#fff'
}

// 选择预设颜色
const selectPresetColor = (color) => {
  formData.color = color
}

// 颜色选择器变化
const handleColorChange = (color) => {
  if (color) {
    formData.color = color
  }
}

// 颜色输入框变化
const handleColorInput = (value) => {
  // 自动添加#号
  if (value && !value.startsWith('#')) {
    formData.color = '#' + value
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    color: '#409EFF'
  })
  formRef.value?.resetFields()
}

// 关闭对话框
const handleClose = () => {
  resetForm()
  // 通知父组件清空数据
  emit('update:tagData', null)
  emit('update:visible', false)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    const submitData = {
      name: formData.name,
      color: formData.color
    }
    
    if (isEdit.value) {
      submitData.id = formData.id
    }
    
    let response
    if (isEdit.value) {
      response = await updateTag(submitData)
    } else {
      response = await createTag(submitData)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      emit('success')
      handleClose()
    }
  } catch (error) {
    console.error('提交失败:', error)
    if (error !== 'validation failed') {
      ElMessage.error('操作失败，请重试')
    }
  } finally {
    submitLoading.value = false
  }
}

// 监听标签数据变化，填充表单
watch(() => props.tagData, (newData) => {
  if (newData) {
    Object.assign(formData, {
      id: newData.id,
      name: newData.name,
      color: newData.color || '#409EFF'
    })
  }
}, { immediate: true })

// 监听对话框打开，重置表单
watch(dialogVisible, (visible) => {
  if (visible) {
    // 每次打开都先重置表单，避免数据残留
    resetForm()
    // 如果是编辑模式，在下一个tick重新设置数据
    if (props.tagData) {
      nextTick(() => {
        Object.assign(formData, {
          id: props.tagData.id,
          name: props.tagData.name || '',
          color: props.tagData.color || '#409EFF'
        })
      })
    }
  }
})
</script>

<style scoped>
.tag-form {
  padding: 0 20px;
}

.color-picker-row {
  display: flex;
  align-items: center;
}

.preview-placeholder {
  font-size: 14px;
  color: #999;
  font-style: italic;
}

.color-preview {
  font-weight: 600;
  border: none;
  font-size: 14px;
  padding: 8px 16px;
}

.preset-colors {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.preset-color-item {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  cursor: pointer;
  border: 2px solid transparent;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.preset-color-item:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.preset-color-item.active {
  border-color: #333;
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.dialog-footer {
  text-align: right;
}

:deep(.el-color-picker__trigger) {
  width: 60px;
  height: 40px;
}

:deep(.el-input__inner) {
  text-transform: uppercase;
}
</style>
